
var app_url=location.origin;
var EDITMODE=false; 

(function(){
	var team = {
		init: function(){
			LoadUser();
			this.bindEvents();
		},
		bindEvents:function(){
			var self = this;
			//点击行展开详情
			$("#stock_body").on("click", "tr td", function () {
			    var td_input = $(this).index();
			    if (td_input == 0 || td_input==9) {
			        //勾选框不展开详情
			    } else {
			        $(this).parent("tr").next(".stock_detail").slideToggle(0);
			    }
			});
			//筛选
			$("#confirm_btn").on("click",function(){
				LoadUser();//获取客户列表
				myApp.closeModal(".user_filter_box");
			});
			//状态筛选
			$(".list_user").on("click", ".term li", function () {
			    $(this).toggleClass("add_blue").siblings().removeClass("add_blue");
			});
			$("#show_term_btn").on("click", function () {
				myApp.popup(".user_filter_box");
			});
			//职能筛选
			$("#_sysStatus>ul").on("click", "li", function () {
				$(this).addClass("add_blue").siblings().removeClass("add_blue");
				LoadUser();//获取客户列表
			});
			//列表的勾选框
			$("#stock_body").on("click",".check_rel",function(){
				$(this).find(".check_list_box").children("span").toggleClass("selected");
			});
			//重置
			$("input[type=reset]").on("click",function(){
				$("#_role li").removeClass("add_blue").css("background","#a1a1a1");
			});
			
			//添加
			$("#add_btn").on("click",function(){
				if(RoleID == 1){
					EDITMODE = false;
					myApp.popup(".add_box");
	//				$(".team_handle_box form").removeClass("edit_form").addClass("add_form");
					if(APP){
				   		var appJson={};
						appJson.title=_("添加团队");
						YiYi_APP.showNewPage(JSON.stringify(appJson));
				    }else{
						$(".add_box h5").html(_("添加团队"));
				   }
				}else{
					toast(_("禁用"));
				}
			});
			//编辑
            $("#stock_body").on("click","td span.modify_btn",function(){
            	EDITMODE = true;
            	myApp.popup(".edit_box");
//          	$(".team_handle_box form").removeClass("add_form").addClass("edit_form");
            	var id=$(this).attr("value");
            	self.bindData(id);
            	
				if(APP){
			   		var appJson={};
					appJson.title=_("编辑团队");
					YiYi_APP.showNewPage(JSON.stringify(appJson));
			  }else{
					$(".edit_box h5").html(_("编辑团队"));
			  }
            });
			//帐号已注册
            jQuery.validator.addMethod("UserNameIsExist", function (value, element) {    //用jquery ajax的方法验证电话是不是已存在  
                var flag = 1;
                $.ajax({
                    url: "/Team/UserRegIsExist",//提交地址
                    type: "POST",//提交方式
                    data: "{'UserName':'" + $("#UserName").val().trim() + "'}",
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象                    
                        if (_result['msgcode'] == false) {
                            flag = 0;
                        }
                    },
                    error: function (err) {
                        alert("err:" + err);
                    }
                });
                if (flag == 1) {
                    return true;

                } else {
                    return false;
                }
            }, "已注册");//帐号已被注册

            //手机号已注册
            jQuery.validator.addMethod("MobileIsExist", function (value, element) {    //用jquery ajax的方法验证电话是不是已存在  
                var flag = 1;
                $.ajax({
                    url: "/Team/UserRegIsExist",//提交地址
                    type: "POST",//提交方式
                    data: "{'Mobile':'" + $("#Mobile").val() + "'}",
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    success: function (result) {
                        var _result = eval('(' + result + ')');//eval()解析单个json对象                    
                        if (_result['msgcode'] == false) {
                            flag = 0;
                        }
                    },
                    error: function (err) {
                        alert("err:" + err);
                    }
                });
                if (flag == 1) {
                    return true;

                } else {
                    return false;
                }
            }, "已注册");//手机号已被注册
            

 
			 //添加团队输入验证 class=add_form
            var validate = $(".add_form").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    self.AddUser();//添加团队
                },
                rules: {
                    UserName: { //name
                        required: true,
                        UserNameIsExist:true,//检查团队帐号是否存在 8-31
                    },
                    UserPassword:"required",
                    RealName: "required",
                    RoleID: "required",
                },
                messages: {
                    UserName: "",
                    UserPassword:  "",
                    RealName:  "",
                    RoleID:  "",
                }
            });
 			
 			//修改团队输入验证 class=edit_form
            var validate = $(".edit_form").validate({
                debug: true, //调试模式取消submit的默认提交功能   
                focusInvalid: false, //当为false时，验证无效时，没有焦点响应  
                onkeyup: false,
                submitHandler: function (form) {   //表单提交句柄,为一回调函数，带一个参数：form   
                    self.AddUser();
                },
                rules: {
                    UserName:"required",
                    UserPassword:"required",
                    RealName:"required",
                    RoleID: "required",
                },
                messages: {
                    UserName: "",
                    UserPassword:  "",
                    RealName:  "",
                    RoleID:  "",
                }
            });
        
		},
		//编辑时绑定数据
		bindData:function(ID){
		    myApp.showIndicator();//显示加载中
			$("#reset_btn").hide();
			var self=this;
			var submitJson={};
			submitJson.UserID=ID;
	
			$.ajax({
				url:'/Team/GetUserInfo',
				type:'POST',
				data: JSON.stringify(submitJson),
				dataType:'JSON',
				contentType: "application/json; charset=utf8",
				success:function(result){
					var data=eval('(' + result + ')')
						$("#edit_data").setForm(data);//帮数据
						$("#id_input").prop({"name":"UserID","value":data.UserID});//ID	
						$("#combo_sales [value='" + data.SalesUserID + "']").prop("selected", true);//下拉框
                        $("#combo_purchases [value='" + data.PurchaseUserID + "']").prop("selected", true);//下拉框
						myApp.hideIndicator();//隐藏加载中					
				}
			});
		},
		AddUser:function(){
		    var self=this;
	        if(EDITMODE){
	        	var finalRes = $('.edit_form').serializeArray().reduce(function(result, item){
	            result[item.name] = item.value;
	            return result;
	        }, {})//把提交的数据转为JSON格式
	        	var submitUrl="/Team/EditUser";
	        }else{
	        	var finalRes = $('.add_form').serializeArray().reduce(function(result, item){
	            result[item.name] = item.value;
	            return result;
	        }, {})//把提交的数据转为JSON格式
	        	var submitUrl="/Team/AddUser";
	        }
	        
	         $.ajax({
		        url: submitUrl,//提交地址
		        type: "POST",//提交方式
		        data: JSON.stringify(finalRes),
		        contentType: "application/json; charset=utf-8",
		        success: function (result) {
		            var _result = eval('(' + result + ')');//eval()解析单个json对象
                    if(_result.msgcode == true){
                        myApp.alert(_(_result.msginfo),function(){
                            LoadUser();
                            $(".edit_box").hide();
                        });
                    }else{
                        myApp.alert(_(_result.msginfo));
                    }
		        }
		    });
			
		},
		
	}
	team.init();
})();
//获取参数
function getParamer() {
    var requestUser = {};

    if(RoleID ==3 || RoleID ==4 || RoleID ==5){
        requestUser.UserID = UserID;
    }
    requestUser.PageSize = 200;
    requestUser.PageIndex = 1;
    requestUser.SysStatus = $("#_sysStatus>ul li.add_blue").attr("data-value");//下拉框
    requestUser.UserName = $.trim($("#_userName").val());
    requestUser.Mobile = $.trim($("#_mobile").val());
    requestUser.RoleID = $("#_role>ul li.add_blue").attr("value");

    return requestUser;
}

 //排序用的
function sort_startSearch(p) {
    LoadUser(p);
}
//加载
function LoadUser(p) {
    myApp.showIndicator();//显示加载中
    if (p) {
        var requestUser = p;
    } else {
        var requestUser = getParamer(requestUser);
    }
    $.ajax({
        url: "/Team/GetUsers",//提交地址
        type: "POST",//提交方式
        data: JSON.stringify(requestUser),
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            BindingData(result, $("#stock_body"));//绑定
            var _result = eval('('+result+')');
//                  _result = _result.Data;//object
            myApp.hideIndicator();//隐藏加载中
            if(requestUser.SysStatus==2){
                $("#wait_user").html(_result.TotalCount);//客户总数
            }
            $.ajax({
                url: "/Team/GetJobTitleInfo",//获取职能角色
                type: "post",//提交方式
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    _result=JSON.parse(result);
                    var options_roles;
                    if(_result.msgcode == false){
                        var options_roles = "";
                        options_roles += '<option value="">' + _(_result.msginfo) + '</option>';
                        $("#RoleID").html("");
                        $("#_RoleID").html("");
                        $("#RoleID").html(options_roles);
                        $("#_RoleID").html(options_roles);

                    }else{
                        $("#RoleID").html("");
                        $("#_RoleID").html("");
                        var options_roles = "";
                        options_roles += '<option value="">--'+_("职能")+'--</option>';
                        _result=_result.msginfo;
                        for (var i = 0; i < _result.length; i++) {
                            if(_result[i].JobTitle!="")
                                options_roles += '<option value="' + _result[i].ID + '"  title="'+_result[i].JobTitle+'"  >' + _(_result[i].JobName) + '</option>';
                            else
                                options_roles += '<option value="' + _result[i].ID + '"   >' + _(_result[i].JobName) + '</option>';
                        }

                        $("#RoleID").html(options_roles);
                        $("#_RoleID").html(options_roles);
                    }
                }
            });
        }

    });
}

//绑定数据
function BindingData(Datas, tableTbody) {
    myApp.showIndicator();
    var _result = eval('(' + Datas + ')');//eval()解析单个json对象

    $("#_totalCount").html(_result.TotalCount);//团队总数

    if (_result.msgcode == false) {
        var tr = "";//单行
        var tds = "<td colspan='50' style='text-align:center;color:red'>" + _(_result.msginfo) + "</td>";// 多列合成一列并居中
        tr = "<tr>" + tds + "</tr>";//将多列加到一行
        tableTbody.html(tr);//加入到id为customer的table的tbody中
        myApp.hideIndicator();  //数据加载完成后去除全屏遮罩层

    } else {

        _result = _result.Data;//object
        var trs = "";//多行数据

        for (var i = 0; i < _result.length; i++) {

            var tds = "";//多列
            var tr = "";//单行
            var tr_div = "";

            tds += "<td class='check_rel'>"+
                "<div class='check_list_box'><span class='checkbox' name='checkbox' lang='" + _result[i].UserID + "'></span></div>";
            tds += "<td>" + _result[i].UserName + "</td>";
            tds += "<td>" + NullFormat(_result[i].RealName) + "</td>";
            tds += "<td>" + RoleIDFormat(_result[i].RoleID) + "</td>";
            tds += "<td>" + NullFormat(_result[i].Department) + "</td>";
            tds += "<td>" + sexFormat(_result[i].Sex) + "</td>";
            tds += "<td>" + _result[i].LoginCount + "</td>";  //次数
            tds += "<td title='"+_result[i].LastActiveTime+"'>" + DateTimeHandler(_result[i].LastActiveTime) + "</td>";  //上次
            tds += "<td>" + sysStatusFormat(_result[i].SysStatus) + "</td>";  //状态

            //根据状态显示操作按钮 -1 已删  0禁止 1正常 2待审
            if (_result[i].SysStatus == -1) {
                tds += "<td class='check_toolbtn'></td>";
            }else if(RoleID == 1){
                tds += "<td  class='check_toolbtn'><span class='modify_btn' title='修改团队' value='" + _result[i].UserID + "'>"+_("修改")+"</span></td>"; //<span class='' title='删除团队' value='" + _result[i].UserID + "'>删除</span>
            }
            else {
                tds += "<td class='check_toolbtn'></td>";
            }

            tr += "<tr class='data_tr'>" + tds + "</tr>";//将多列加到一行
            tr_div="<tr class='stock_detail'><td  colspan='50'>"+
                "<div class='detail_left' style='width:50%;'>"+
                "<i><b>"+_("电话")+"：</b>"+NullFormat(_result[i].Mobile)+"</i>"+
                "<i><b>"+_("邮箱")+"：</b>" + NullFormat(_result[i].Email) + "</i>"+
                "<i><b class='custrom'>QQ：</b><span>" + NullFormat(_result[i].Qq) + "</span></i>"+
                "<i><b>Skype：</b>" +  NullFormat(_result[i].Skype) + "</i>"+
                "<i><b>RapID：</b>" +  _result[i].RapnetAccount + "</i>"+
                "</div>" +
                "<div class='detail_middle' style='width:50%;'>"+
                "<i><b>IP：</b>" + NullFormat(_result[i].ActiveIP) + "</i>" +
                "<i><b>"+_("更新")+"：</b>" + DateTimeFormat(_result[i].UpdateTime) + "</i>"+
                "<i><b class='custrom'>"+_("创建")+"：</b><span>" + DateTimeFormat(_result[i].CreateTime) + "</span></i>" +

                "</div></td></tr>";
            trs += tr+tr_div;//将单行加到多行
        }
        tableTbody.html(trs);//加入到id为customer的table的tbody中
        myApp.hideIndicator();  //数据加载完成后去除全屏遮罩层
    }
}






